package com.mywang.weitravel.modules.mine;

import com.mywang.weitravel.base.BasePresenter;
import com.mywang.weitravel.model.CollectionResponse;
import com.mywang.weitravel.net.RetrofitHelper;
import com.mywang.weitravel.net.RxSchedulers;
import com.mywang.weitravel.net.VObserver;

import java.util.ArrayList;
import java.util.Collection;

public class CollectionPresenter extends BasePresenter<CollectionContract.View> implements CollectionContract.Presenter {

    private int page = 1;

    public CollectionPresenter(CollectionContract.View view) {
        super(view);
    }

    @Override
    public void onRefresh() {
        page = 1;
        loadData();
    }

    @Override
    public void onLoadMore() {
        loadData();
    }

    private void loadData() {
        RetrofitHelper.getInstance().getServer()
                .getCollectionList(page)
                .compose(RxSchedulers.applySchedulers())
                .as(bindToLife())
                .subscribe(new VObserver<CollectionResponse>() {
                    @Override
                    protected void onSuccess(CollectionResponse collectionResponse) {
                        if (collectionResponse != null) {
                            if (page == 1) {
                                if (isCollectionEmpty(collectionResponse.list)) {
                                    mView.noData();
                                } else {
                                    mView.onRefreshSuccessful(collectionResponse.list, canLoadMore(collectionResponse));
                                }
                            } else {
                                mView.onLoadMoreSuccessful(collectionResponse.list, canLoadMore(collectionResponse));
                            }
                        } else {
                            if (page == 1) {
                                mView.noData();
                            } else {
                                mView.onLoadMoreSuccessful(new ArrayList<>(), false);
                            }
                        }
                        page++;
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        mView.refreshOrLoadMoreCompleted();
                    }
                });
    }

    private boolean isCollectionEmpty(Collection collection) {
        return collection == null || collection.isEmpty();
    }

    private boolean canLoadMore(CollectionResponse collectionResponse) {
        return collectionResponse != null && isCollectionEmpty(collectionResponse.list) && collectionResponse.list.size() >= collectionResponse.per_page;
    }
}
